const Fs = require('fs')

const TodoListJson = './src/json/todoList.json'
const UidJson = './src/json/uid.json'

async function routes(fastify, options) {

    // 登录接口
    fastify.post('/api/login', (request, reply) => {
        const body = request.body
        if (body.name === 'kmhome' && body.pwd === 'kmhome123456') {
            reply.send({
                result: 'right'
            })
        } else {
            reply.send({
                result: 'error'
            })
        }
    })

    // 获取全部 todoList
    fastify.get('/api/getTodoList', (request, reply) => {
        const dataStr = Fs.readFileSync(TodoListJson, {
            encoding: 'utf-8'
        })
        reply.send(JSON.parse(dataStr))
    })

    // 新增 todoList
    fastify.post('/api/addOneTodo', (request, reply) => {
        const body = request.body
        const dataStr = Fs.readFileSync(TodoListJson, {
            encoding: 'utf-8'
        })
        const data = JSON.parse(dataStr)
        // 取 uid
        const uidStr = Fs.readFileSync(UidJson, {
            encoding: 'utf-8'
        })
        const uid = JSON.parse(uidStr).max
        const id = uid
        data.push({ ...body, id: id })
        Fs.writeFileSync(UidJson, JSON.stringify({ max: uid + 1 }), { encoding: 'utf-8' })
        Fs.writeFileSync(TodoListJson, JSON.stringify(data), { encoding: 'utf-8' })
        reply.send(data)
    })

    // 修改 todoList
    fastify.post('/api/changeOneTodo', (request, reply) => {
        const body = request.body
        const dataStr = Fs.readFileSync(TodoListJson, {
            encoding: 'utf-8'
        })
        const data = JSON.parse(dataStr)
        // 通过 id 找到
        for (let i = 0; i < data.length; i++) {
            if (data[i].id === body.id) {
                data[i] = { ...body }
            }
        }
        Fs.writeFileSync(TodoListJson, JSON.stringify(data), { encoding: 'utf-8' })
        reply.send(data)
    })

    // 删除 todoList
    fastify.post('/api/removeTodos', (request, reply) => {
        const body = request.body
        const dataStr = Fs.readFileSync(TodoListJson, {
            encoding: 'utf-8'
        })
        const data = JSON.parse(dataStr)
        // 需要删除的 ids
        const ids = body.ids
        for (let i = 0; i < ids.length; i++) {
            const needDeleteId = ids[i]
            const index = data.findIndex(v => v.id === needDeleteId)
            if (index !== -1) {
                data.splice(index, 1)
            }
        }
        Fs.writeFileSync(TodoListJson, JSON.stringify(data), { encoding: 'utf-8' })
        reply.send(data)
    })
}

module.exports = routes